// =================================================================
// File: mkdir.cpp
// Desc: Contains function for making a directory
// =================================================================

// =================================================================
// INCLUDES
// =================================================================

#include <string>
#include "FSManager.h"
#include "commands.h"
#include "Directory.h"
#include "Inode.h"

using namespace std;

// =================================================================
// FUNCTIONS
// =================================================================

// =================================================================
// Name: mkdir
// Desc: Creates a directory with the specified name
// Args: string dir_name - the directory to create
//       FSManager* fsm - pointer to active FSManager object
// =================================================================
void mkdir(string dir_name, FSManager *fsm){
  
  int inode_index;
  Inode *node = new Inode();
  Directory *newDir;
  Directory *currDir;

  if(dir_name[dir_name.length()-1] == '/'){
    dir_name.erase(dir_name.length()-1,1);
  }

  inode_index = fsm->GetSB()->FreeInodePop();

  node->SetNumLinks(1);

  size_t found = dir_name.find_last_of("/");
  if(found == string::npos){
    currDir = fsm->GetCurrentDirectory();
  }else{
    currDir = fsm->ReadDirectory(dir_name.substr(0,found));
  }
  
  newDir = new Directory(inode_index,currDir->GetInodeIndex());

  dir_name = dir_name.substr(found+1);
  if(dir_name[dir_name.length()-1] != '/'){
  dir_name += '/';
  }

  currDir->InsertEntry(dir_name,inode_index);

  fsm->WriteInode(node,inode_index);
  fsm->WriteDirectory(newDir);
  fsm->WriteDirectory(currDir);

  delete newDir;
  delete node;
  
  cout << "Directory " << dir_name << " created." << endl;
}
